package com.googlecode.jsonld4j.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class IOUtil {
	/**
	 * Get the input stream from an address. The address can be a resource file
	 * in a jar, a filename or a url address
	 * 
	 * @param address
	 * @return InputStream
	 * @throws IOException
	 */
	public static InputStream getInputStream(String address) throws IOException {
		// try first resource in jar
		InputStream is = getResourceInputStream(address);
		if (is != null)
			return is;
		// then try file
		File f = new File(address);
		if (f.exists())
			try {
				return new FileInputStream(f);
			} catch (FileNotFoundException e) {
				throw new IOException(e.getMessage());
			}
		return new URL(address).openStream();
	}
	
	public static InputStream getResourceInputStream(String resourceName) {
        InputStream result = null;
        result = IOUtil.class.getResourceAsStream(resourceName);
        if (result == null) {
            result = IOUtil.class.getClassLoader().getResourceAsStream(resourceName);
            if (result == null) {
                result = ClassLoader.getSystemResourceAsStream(resourceName);
            }
        }
        return result;
    }

	/**
	 * Get the content from an address as a string. The address can be a
	 * resource file in a jar, a filename or a url address
	 * 
	 * @param address
	 * @return string
	 * @throws IOException
	 */
	public static String readAsString(String address)
			throws java.io.IOException {
		StringBuffer fileData = new StringBuffer(1000);
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				getInputStream(address)));
		char[] buf = new char[1024];
		int numRead = 0;
		while ((numRead = reader.read(buf)) != -1) {
			String readData = String.valueOf(buf, 0, numRead);
			fileData.append(readData);
			buf = new char[1024];
		}
		reader.close();
		return fileData.toString();
	}

	/**
	 * Get the content as a string from an input stream.
	 * 
	 * @param input
	 *            stream
	 * @return string
	 * @throws IOException
	 */
	public static String readAsString(InputStream is)
			throws java.io.IOException {
		StringBuffer fileData = new StringBuffer(1000);
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		char[] buf = new char[1024];
		int numRead = 0;
		while ((numRead = reader.read(buf)) != -1) {
			String readData = String.valueOf(buf, 0, numRead);
			fileData.append(readData);
			buf = new char[1024];
		}
		reader.close();
		return fileData.toString();
	}

}
